package com.ztgf.shopping.service.shop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.BrandInfoDTO;
import com.ztgf.commodity.models.dto.CommodityCategoryDTO;
import com.ztgf.commodity.models.service.IBrandInfoService;
import com.ztgf.commodity.models.service.ICommodityCategoryService;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopQualificationMapper;
import com.ztgf.shopping.models.bo.shop.ShopQualificationBO;
import com.ztgf.shopping.models.bo.shop.ShopQualificationSaveBO;
import com.ztgf.shopping.models.dto.shop.ShopBrandRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopCategoryRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopQualificationDTO;
import com.ztgf.shopping.models.service.shop.IShopBrandRelationService;
import com.ztgf.shopping.models.service.shop.IShopCategoryRelationService;
import com.ztgf.shopping.models.service.shop.IShopQualificationService;
import com.ztgf.shopping.models.vo.shop.CommodityCategoryTreeVO;
import com.ztgf.shopping.models.vo.shop.ShopQualificationBrandVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺资质表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-28 14:40:54
 */
@DubboService
public class ShopQualificationServiceImpl extends ServiceImpl<ShopQualificationMapper, ShopQualificationDTO> implements IShopQualificationService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private IShopBrandRelationService shopBrandRelationService;
    @DubboReference
    private IBrandInfoService iBrandInfoService;
    @Autowired
    private IShopCategoryRelationService iShopCategoryRelationService;
    @DubboReference
    private ICommodityCategoryService iCommodityCategoryService;

    /**
     * 根据类型返回资质过期的数量
     *
     * @param id
     * @return
     */
    public Integer getExpireAudisNumByShopId(Long id, List<Integer> typeList) {
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", id);
        //类型 0营业执照，1法人身份证，2开户许可证，3商标注册证书，4续展证明文件，5ISO认证书，6品牌授权书
        wrapper.in("type", typeList);
        //wrapper.andNew().eq("type", 0).or().eq("type", 1).or().eq("type",2);
        // 到期状态 0正常，1即将到期，2已过期
//        wrapper.andNew().eq("expire_status", 1).or().eq("expire_status", 2);
        wrapper.eq("expire_status",2);
        return selectList(wrapper).size();
    }

    @Override
    public boolean add(ShopQualificationSaveBO saveBO) {
        ShopQualificationDTO dto = new ShopQualificationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 判断基本资质是否有过期
     *
     * @param shopId
     * @return
     */
    @Override
    public boolean getIsExpire(Long shopId) {
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("expire_status", 2);
        wrapper.eq("shop_id", shopId);
        wrapper.in("type", Arrays.asList(0, 1, 2));
        return selectList(wrapper).size() > 0;
    }

    @Override
    public List<ShopQualificationBrandVO> queryBrandList(Long shopId) {
        ArrayList<ShopQualificationBrandVO> vos = new ArrayList<ShopQualificationBrandVO>();
        /**
         * 1获取店铺品牌关联
         * 2获取品牌下所有资质
         */
        Wrapper<ShopBrandRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.andNew().eq("status", 0).or().eq("status", 2);//正常或者过期
        List<ShopBrandRelationDTO> shopBrandRelationDTOList = shopBrandRelationService.selectList(wrapper);
        for (ShopBrandRelationDTO shopBrandRelationDTO : shopBrandRelationDTOList) {
            BrandInfoDTO brandInfoDTO = iBrandInfoService.selectById(shopBrandRelationDTO.getBrandId());
            ShopQualificationBrandVO vo = new ShopQualificationBrandVO();
            vo.setId(brandInfoDTO.getId());
            vo.setName(brandInfoDTO.getName());
            vo.setLogoUrl(brandInfoDTO.getLogoUrl());

            Wrapper<ShopQualificationDTO> sQWrapper = new EntityWrapper<>();
            sQWrapper.eq("shop_id", shopId).eq("brand_id", shopBrandRelationDTO.getBrandId());
            vo.setShopQualificationDTOList(this.selectList(sQWrapper));
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public ShopQualificationBrandVO queryBrandQCList(ShopQualificationBO bo) {
        ShopQualificationBrandVO vo = new ShopQualificationBrandVO();
        BrandInfoDTO brandInfoDTO = iBrandInfoService.selectById(bo.getBrandId());
        vo.setId(brandInfoDTO.getId());
        vo.setName(brandInfoDTO.getName());
        vo.setLogoUrl(brandInfoDTO.getLogoUrl());

        //品牌资质
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", bo.getShopId()).eq("brand_id", bo.getBrandId());
        vo.setShopQualificationDTOList(this.selectList(wrapper));

        //品牌类目
        Wrapper<ShopCategoryRelationDTO> srWrapper = new EntityWrapper<>();
        srWrapper.eq("shop_id", bo.getShopId()).eq("brand_id", bo.getBrandId());
        vo.setShopCategoryRelationDTOList(iShopCategoryRelationService.selectList(srWrapper));

        return vo;
    }

    /**
     * 根据店铺id和类型获取信息
     *
     * @param shopId
     * @param type
     * @return
     */
    @Override
    public ShopQualificationDTO getByShopIdAndType(Long shopId, Integer type) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("type", type);
        return selectOne(wrapper);
    }

    @Override
    public ShopQualificationBrandVO queryBrandQCTree(ShopQualificationBO bo) {
        ShopQualificationBrandVO vo = new ShopQualificationBrandVO();
        BrandInfoDTO brandInfoDTO = iBrandInfoService.selectById(bo.getBrandId());
        vo.setId(brandInfoDTO.getId());
        vo.setName(brandInfoDTO.getName());
        vo.setLogoUrl(brandInfoDTO.getLogoUrl());

        //品牌资质
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", bo.getShopId()).eq("brand_id", bo.getBrandId());
        vo.setShopQualificationDTOList(this.selectList(wrapper));

        //品牌类目
        Wrapper<ShopCategoryRelationDTO> srWrapper = new EntityWrapper<>();
        srWrapper.eq("shop_id", bo.getShopId()).eq("brand_id", bo.getBrandId());
        List<ShopCategoryRelationDTO> shopCategoryList = iShopCategoryRelationService.selectList(srWrapper);
        if (shopCategoryList != null && shopCategoryList.size() > 0) {
            List<CommodityCategoryTreeVO> root = new ArrayList<>();
            for (ShopCategoryRelationDTO shopCategoryRelationDTO : shopCategoryList) {
                List<CommodityCategoryTreeVO> byChildId = this.getByChildId(shopCategoryRelationDTO.getCategoryId(), new ArrayList<>());
                root.addAll(byChildId);
            }
            //查询最顶级的类目
            Wrapper<CommodityCategoryDTO> wrapperParent = new EntityWrapper<>();
            wrapperParent.eq("is_publish", 1).eq("status", 0)
                    .eq("parent_id", 0).orderBy("sort", true);
            List<CommodityCategoryDTO> parentList = iCommodityCategoryService.selectList(wrapperParent);
            for (CommodityCategoryDTO commodityCategoryDTO : parentList) {
                CommodityCategoryTreeVO commodityCategoryTreeVO = new CommodityCategoryTreeVO();
                BeanUtils.copyProperties(commodityCategoryDTO, commodityCategoryTreeVO);
                root.add(commodityCategoryTreeVO);
            }
            //去重
            List<CommodityCategoryTreeVO> realRoot = root.stream().distinct().collect(Collectors.toList());
            //构建树形结构
            List<CommodityCategoryTreeVO> list = this.builTree(realRoot);
            List<CommodityCategoryTreeVO> real = new ArrayList<>();
            for (CommodityCategoryTreeVO categoryTreeVO : list) {
                real.addAll(categoryTreeVO.getChildList());
            }
            vo.setShopCategoryRelationDTOTree(real.stream().distinct().collect(Collectors.toList()));
        }
        return vo;
    }

    @Override
    public boolean getExpireStatus(Long shopId, Long brandId) {
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId).eq("brand_id", brandId);
        List<ShopQualificationDTO> dtos = this.selectList(wrapper);
        if (dtos == null || dtos.size() <= 0) {
            return false;
        }

        boolean flag = true;

        for (ShopQualificationDTO dto : dtos) {
            if (dto.getExpireStatus().equals(2)) {
                if (dto.getType()==3){
                    for (ShopQualificationDTO shopQualificationDTO : dtos) {
                        if (dto.getType()==4){
                            flag = false;
                            break;
                        }
                    }
                }else {
                    //有资质过期
                    flag = false;
                }

                break;
            }
        }
        return flag;
    }

    @Override
    public List<ShopQualificationDTO> queryExpire(Long minNo, Integer PageNo) {
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("expire_status", 1);//到期状态 0正常，1即将到期，2已过期
        wrapper.ge("id", minNo);
        wrapper.orderBy("id", true);
        return baseMapper.selectPage(new Page(0, PageNo), wrapper);
    }

    @Override
    public List<ShopQualificationDTO> queryBeforExpire(Long minNo, Integer PageNo) {
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("expire_status", 0);//到期状态 0正常，1即将到期，2已过期
        wrapper.isNotNull("end_date");
        wrapper.ge("id", minNo);
        wrapper.orderBy("id", true);
        return baseMapper.selectPage(new Page(0, PageNo), wrapper);
    }

    /**
     * description: 建立树形结构
     * param: [menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    public List<CommodityCategoryTreeVO> builTree(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> treeMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : getRootNode(menuList)) {
            menuNode = this.buildChilTree(menuNode, menuList);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    /**
     * description: 递归，建立子树形结构
     * param: [pNode, menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: com.ztgf.commodity.models.vo.CommodityCategoryTreeVO
     */
    private CommodityCategoryTreeVO buildChilTree(CommodityCategoryTreeVO pNode, List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> chilMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().equals(pNode.getId())) {
                chilMenus.add(this.buildChilTree(menuNode, menuList));
            }
        }
        pNode.setChildList(chilMenus);
        return pNode;
    }

    /**
     * description: 获取根节点
     * param: [menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    private List<CommodityCategoryTreeVO> getRootNode(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> rootMenuLists = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().intValue() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

    /**
     * description: 根据最终极类目id查询所有上级list
     * param: [id, list]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    public List<CommodityCategoryTreeVO> getByChildId(Long id, List<CommodityCategoryTreeVO> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        CommodityCategoryDTO dto = iCommodityCategoryService.selectById(id);
        if (dto == null) {
            return null;
        }
        if (dto.getParentId() == 0) {
            return list;
        } else {
            CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
            treeVO.setId(dto.getId());
            treeVO.setName(dto.getName());
            treeVO.setInitials(dto.getInitials());
            treeVO.setParentId(dto.getParentId());
            treeVO.setSort(dto.getSort());
            treeVO.setCode(dto.getCode());
            list.add(treeVO);
        }
        return this.getByChildId(dto.getParentId(), list);
    }
}
